package by.grsu.dz.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.dz.entity.Circle;
import by.grsu.dz.table.CircleTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

/**
 * @author dmitry_zhivushko
 * @since Sep 28, 2014
 */
public class CircleDao extends AbstractDao<CircleTable, Circle> {

	public CircleDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Circle newCircle) {
		// set ID
		newCircle.setId(getNextId());
		// get existing data
		final CircleTable circleTable = deserializeFromXml();
		// add new row
		circleTable.getRows().add(newCircle);
		// save data
		serializeToXml(circleTable);
	}

	@Override
	public void update(final Circle entity) {
		// get existing data
		final CircleTable circleTable = deserializeFromXml();
		// find by ID
		for (final Circle row : circleTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setColor(entity.getColor());
				row.setRadius(entity.getRadius());
				break;
			}
		}
		// save updated table
		serializeToXml(circleTable);
	}

	@Override
	public Circle get(final Serializable id) {
		// get existing data
		final CircleTable circleTable = deserializeFromXml();
		// find by ID
		for (final Circle row : circleTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Circle> getAll() {
		// get existing data
		final CircleTable circleTable = deserializeFromXml();
		return circleTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		// get existing data
		final CircleTable circleTable = deserializeFromXml();
		// find by ID
		Circle toBeDeleted = null;
		for (final Circle row : circleTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		circleTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(circleTable);
	}

	@Override
	protected Class<CircleTable> getTableClass() {
		return CircleTable.class;
	}

}
